/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-10-17     hehung       the first version
 */

#include "app_rtc.h"
#include "board.h"

static void RTC_ManageEntry(void *parameter);
static void RTC_ThreadManage(void);


void RTC_AppInit(void)
{
    rt_err_t ret = RT_EOK;

    ret = set_date(2021, 11, 7);     /*Set Date*/
    if (ret != RT_EOK)
    {
        rt_kprintf("set RTC date failed\n");
    }

    ret = set_time(21, 20, 48);       /*Set Time*/
    if (ret != RT_EOK)
    {
        rt_kprintf("set RTC time failed\n");
    }
}

void RTC_DateUpdate(rtc_date paraDate)
{
    rt_err_t ret = RT_EOK;

    ret = set_date(paraDate.m_year, paraDate.m_month, paraDate.m_day);     /*Set Date*/
    if (ret != RT_EOK)
    {
        rt_kprintf("set RTC date failed\n");
    }

    ret = set_time(paraDate.m_hour, paraDate.m_min, paraDate.m_sec);       /*Set Time*/
    if (ret != RT_EOK)
    {
        rt_kprintf("set RTC time failed\n");
    }
}

static void RTC_ManageEntry(void *parameter)
{
    RTC_AppInit();

    while(1)
    {
        struct tm* now;
        now = RTC_GetTime();

        rt_kprintf("20%d-%d-%d|%d:%d:%d\n", now->tm_year, now->tm_mon, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
        rt_thread_mdelay(1000);
    }
}

static void RTC_ThreadManage(void)
{
    rt_thread_t rtc_thread;

    rtc_thread = rt_thread_create("RTC Thread Manage",     /*线程名字*/
                                   RTC_ManageEntry,/*线程入口函数*/
                                   RT_NULL, /*线程入口函数参数*/
                                   2048,    /*线程栈大小*/
                                   2,       /*线程优先级*/
                                   10);     /*线程时间片*/

    if(rtc_thread != RT_NULL)
    {
        rt_kprintf("RTC Thread Created Success!\n");
        rt_thread_startup (rtc_thread);
    }
    else
    {
        rt_kprintf("RTC Thread Create Failed!\n");
    }
}

#ifdef FINSH_USING_MSH
MSH_CMD_EXPORT(RTC_ThreadManage, Get RTC Time);
#endif

struct tm* RTC_GetTime(void)
{
    time_t now_time;

    now_time = time(RT_NULL);

    return (localtime(&now_time));
}

